<?php


namespace app\common\service\sms;


use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsResponseBody;
use app\model\System;
use Darabonba\OpenApi\Models\Config;

/**
 * 阿里云短信
 */
class SmsAliService {

    /**
     * 使用AK&SK初始化账号Client
     * @return Dysmsapi Client
     */
    public static function createClient(): Dysmsapi
    {

        $system = System::getSystem();

        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => $system['sms_ali_id'],
            // 您的AccessKey Secret
            "accessKeySecret" => $system['sms_ali_secret']
        ]);
        // 访问的域名
        $config->endpoint = $system['sms_ali_endpoint'];
        return new Dysmsapi($config);
    }

    /**
     * @param $mobile
     * @param $signName
     * @param $tCode
     * @param array $param
     * @return \AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsResponse
     */
    public static function send($mobile, $signName, $tCode, array $param = []){

        $args = [
            'phoneNumbers' => $mobile,
            'signName' => $signName,
            'templateCode' => $tCode,
        ];

        if (count($param) > 0){
            $args['templateParam'] = json_encode($param);
        }

        $client = self::createClient();
        $sendSmsRequest = new SendSmsRequest($args);
        // 复制代码运行请自行打印 API 的返回值
        $res = $client->sendSms($sendSmsRequest);

        $resb = ($res->toMap())['body'];

        $data = ['error'=>0, 'msg'=>'发送成功'];
        if ($resb['Code'] != 'OK'){  // 发送失败
            $data['error'] = $resb['Code'];
            $data['msg'] = $resb['Message'];
        }

        return $data;

    }

}
